LIBRARY ieee;
USE ieee.std_logic_1164.all;
USE ieee.std_logic_signed.all;
USE work.components.all;

ENTITY decode IS
PORT (  Tick					: IN	STD_LOGIC_VECTOR(2 DOWNTO 0);
		Clock, WriteData		: IN	STD_LOGIC;
		DataIn					: IN	STD_LOGIC_VECTOR(1 DOWNTO 0);
		Instr, Immed, Data		: IN	STD_LOGIC_VECTOR(7 DOWNTO 0);
		R1Out, R2Out, IMOut		: OUT	STD_LOGIC_VECTOR(7 DOWNTO 0);
		Ctrl					: OUT	STD_LOGIC_VECTOR(7 DOWNTO 0));
END decode;

ARCHITECTURE behavior OF decode IS
	SIGNAL R1in, R2in, R3in, R4in		: STD_LOGIC;
	--SIGNAL WB, EX						: STD_LOGIC;
	--SIGNAL MEM							: STD_LOGIC_VECTOR(1 DOWNTO 0);
	SIGNAL Command						: STD_LOGIC_VECTOR(3 DOWNTO 0);
	SIGNAL ulaOp						: STD_LOGIC_VECTOR(1 DOWNTO 0);
	SIGNAL R1, R2, R3, R4				: STD_LOGIC_VECTOR(7 DOWNTO 0);
	
BEGIN
	regR1: regn PORT MAP (Data, R1in, Clock, R1);
	regR2: regn PORT MAP (Data, R2in, Clock, R2);
	regR3: regn PORT MAP (Data, R3in, Clock, R3);
	regR4: regn PORT MAP (Data, R4in, Clock, R4);
	
	regs: 		registers 	PORT MAP (Instr, R1, R2, R3, R4, Immed, R1Out, R2Out);
	ctrler: 	controlunit	PORT MAP (Instr, Command(3 DOWNTO 2), Command(1), Command(0));
	ulaDecod: 	ulaDecoder 	PORT MAP (Instr(7 DOWNTO 4), ulaOp);
	
	CTRL(1 DOWNTO 0) <= Instr(3 DOWNTO 2);
	WITH Instr SELECT
		Ctrl(3 DOWNTO 2) <= "00" WHEN "00000000",
							ulaOp WHEN OTHERS;
	WITH Instr SELECT
		Ctrl(7 DOWNTO 4) <= "0000" WHEN "00000000",
							Command WHEN OTHERS;
							
	dataEnter: PROCESS(DataIn)
	BEGIN
		R1in <= '0'; R2in <= '0';
		R3in <= '0'; R4in <= '0';
		CASE DataIn IS
			WHEN "00" =>
				R1in <= WriteData;
			WHEN "01" =>
				R2in <= WriteData;
			WHEN "10" =>
				R3in <= WriteData;
			WHEN "11" =>
				R4in <= WriteData;
		END CASE;
	END PROCESS;
		

	IMOut <= Immed;
END behavior;